package com.oocl.scan.jdt.parser;

import com.oocl.scan.model.SoapConfig;
import com.oocl.scan.store.SoapConfigStore;
import com.oocl.scan.utils.StringUtil;
import com.oocl.scan.utils.XMLUtil;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.dom4j.Document;
import org.dom4j.Element;

public class SoapConfigParser {

  public void parserSoapConfig(String filePath) {
    Document document = XMLUtil.parseXmlToDocument(filePath);
    buildRestDtoAndURLFromSoapConfig(document);
  }

  private void buildRestDtoAndURLFromSoapConfig(Document document) {
    List<Element> subComponents = document.getRootElement().elements();
    for (Element subComponent : subComponents) {
      String dtoName = subComponent.attributeValue("name");
      buildWSRest(subComponent, dtoName);
    }
  }

  private void buildWSRest(Element subComponent, String dtoName) {
    dtoName = getFullDtoName(dtoName);
    if (isIRISClassName(dtoName)) {
      for (Element element : (List<Element>) subComponent.elements()) {
        if (element.attributeValue("name").equals("WEB_SERVICE_URL")) {
          String URL = getURLBeginWithModuleName(element.attributeValue("value"));
          if (URL != null) {
            SoapConfigStore.getInstance().add(new SoapConfig(URL, dtoName, null, true));
          }
        }
        break;
      }
    }
  }

  private static String getURLBeginWithModuleName(String url) {
    String targetURL = null;
    if (url != null) {
      Pattern pattern = Pattern.compile("wls_dom_[(a-z)]+");
      Matcher matcher = pattern.matcher(url);
      if (matcher.find()) {
        targetURL = url.substring(url.indexOf(matcher.group()));
      }
    }
    return targetURL;
  }

  private boolean isRestFul(String name) {
    return StringUtil.isIncludeSubStr(name, "FWRESTServiceProxy") || StringUtil.isIncludeSubStr(name, "NewProxy");
  }

  private String getFullDtoName(String name) {
    return removeFwProxy(name);
  }

  private String removeFwProxy(String dtoName) {
    if (isRestFul(dtoName)) {
      return dtoName.substring(dtoName.indexOf("(") + 1, dtoName.length() - 1);
    }
    return dtoName;
  }

  private boolean isIRISClassName(String dtoName) {
    return Pattern.compile("com.oocl.*.").matcher(dtoName).find();
  }
}
